package com.lianyi.push.share.tcpservice;

import android.content.Context;

import com.lianyi.push.share.ConstantValue;
import com.lianyi.push.share.channelinitializer.TcpServiceChannelInitializer;
import com.lianyi.push.share.listener.TcpClientToSeiviceMessageListener;
import com.lianyi.push.util.LogUtil;
import com.lianyi.push.util.Preconditions;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Created by leilei on 2018/4/8.
 */

public class TcpService {
    private ExecutorService executorService = Executors.newFixedThreadPool(ConstantValue.TCP_MAX_COUNT);
    private TcpClientToSeiviceMessageListener tcpClientToSeiviceMessageListener;
    private Context mContext;

    private TcpService() {
    }

    public void setOnTcpClientToSeiviceMessageListener(TcpClientToSeiviceMessageListener listener) {
        this.tcpClientToSeiviceMessageListener = listener;
    }


    public void init(Context context) {
        this.mContext = context;
    }

    private static class SingletonHolder {
        private static final TcpService INSTANCE = new TcpService();
    }

    public static TcpService getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public synchronized void StartTcpService(TcpClientToSeiviceMessageListener tcpServerListener) {
        Preconditions.checkNotNull(tcpServerListener, "TcpService StartTcpService TcpClientToSeiviceMessageListener isNull");
        this.tcpClientToSeiviceMessageListener = tcpServerListener;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                TcpService.getInstance().StartService();
            }
        });
    }

    public void StartService() {
        EventLoopGroup bossGroup = null;// 连接处理group
        EventLoopGroup workerGroup = null;// 事件处理group
        try {
            bossGroup = new NioEventLoopGroup();
            workerGroup = new NioEventLoopGroup();
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)// 绑定处理group
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, ConstantValue.TCP_SO_BACKLOG)// 保持最大连接数
                    .childOption(ChannelOption.TCP_NODELAY, true)//是否禁用nagle算法,true为禁用
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//保持长连接2小时判断一次
//                    .option(ChannelOption.SO_REUSEADDR, true)//地址复用
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .localAddress(new InetSocketAddress(ConstantValue.TCP_PORT))
//                    .childHandler(new ChannelInitializer<SocketChannel>() {
//                        @Override
//                        protected void initChannel(SocketChannel ch) throws Exception {
////                            ch.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
////                            ch.pipeline().addLast(new SmartCarEncoder());
////                            ch.pipeline().addLast(new SmartCarDecoder());
////                            ch.pipeline().addLast(new ServerHandler(tcpServerListener));
//                            ch.pipeline().addLast(new ObjectDecoder(1024 * 1024 * 1024,
//                                    ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
//                            ch.pipeline().addLast(new ObjectEncoder());
//                            ch.pipeline().addLast(new TcpServerHandler(tcpClientToSeiviceMessageListener));
//                        }
//                    })
                    .childHandler(new TcpServiceChannelInitializer(tcpClientToSeiviceMessageListener))

            ;
            //绑定端口，同步等待成功
            ChannelFuture f = b.bind().sync();
            if (f.isSuccess()) {
                LogUtil.e("服务器连接客户端启动成功", "服务器连接客户端启动成功");
            } else {
                LogUtil.e("服务器连接客户端启动失败", "服务器连接客户端启动失败");
            }
            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅退出，释放线程池资源
            if (bossGroup != null) {
                bossGroup.shutdownGracefully();
            }
            if (workerGroup != null) {
                workerGroup.shutdownGracefully();
            }
        }
    }
}
